<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div id="root" onclick="topay">
    <span>
      <a></a>
    </span>
    <span>
      <a></a>
      <a></a>
    </span>
  </div>
  <!-- {
    tag: 'DIV',
    children: [
      {
        tag: 'SPAN',
        children: [
          { tag: 'A', children: [] }
        ]
      },
      {
        tag: 'SPAN',
        children: [
          { tag: 'A', children: [] },
          { tag: 'A', children: [] }
        ]
      }
    ]
  } -->

  <div id='root2'>11111111
    <span>span标签1
      <a href="#">a连接</a>
      <div>
        div
        <a>这是另一个a标签</a>
      </div>
    </span>
    <span>
      这是span标签2
      <p>这是一个p标签</p>
    </span>
  </div>
  <script>
    const domtree = document.getElementById('root')
    console.log('domtree:',domtree);
    console.log('domtree.children==========');
    const children = domtree.children
    console.log(children,typeof children);
    console.log('Object.keys',Object.keys(children));
    console.log('domtree.childNodes==========');
    const childNodes = domtree.childNodes
    console.log(childNodes,typeof childNodes);
    

    console.log('方法一开始=====');
    function dom2Json(domtree) {
      let obj = {}
      obj.children = []
      obj.tag = domtree.tagName
      Object.keys(domtree.children).forEach(child => {
        obj.children.push(dom2Json(domtree.children[child]))
      });
      return obj
    }
    console.log(dom2Json(domtree))


    console.log('方法二开始=====');
    function dom2Json2(domtree){
      let obj = {}
      obj.children = []
      obj.tag = domtree.tagName
      domtree.childNodes.forEach(child=>{
        console.log(child.tagName);
        if(child.tagName){
          obj.children.push(dom2Json2(child))
        }
      })
      return obj
    }
    console.log(dom2Json2(domtree));


    // 广度遍历
    var root2 = document.getElementById('root2')
    function wideTraversal(node) {
      var nodes = []
      if(node != null){
        var queue = []
        queue.push(node)
        while (queue.length) {
          var item = queue.shift()
          nodes.push(item)
          for(var i = 0;i<item.children.length;i++){
            queue.push(item.children[i])
          }
        }
      }
      return nodes
    }
    console.log('root2 广度遍历',wideTraversal(root2));


    // 深度遍历
    function deepTraversal(node) {
      var nodes = []
      var stack = []
      stack.push(node)
      while (stack.length) {
        var item = stack.pop()
        nodes.push(item)
        for(var i = item.children.length-1;i>=0;i--){
          stack.push(item.children[i])
        }
      }
      return nodes
    }
    console.log('root2 广度遍历',deepTraversal(root2));
    
  </script>
</body>
</html>